<template>
  <div>
    <!-- action 是图片上传的地址 -->
    <el-upload
      action="https://jsonplaceholder.typicode.com/posts/"
      list-type="picture-card"
      :on-preview="preview"
      :on-remove="remove"
      :before-upload="beforeUpload"
      :http-request="upload"
      :limit="1"
      :file-list="fileList"
      :class="{ disabled: disabled }"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-progress
      v-if="showProgress"
      :percentage="percentage"
      style="width: 180px"
    ></el-progress>
    <el-dialog title="图片预览" :visible.sync="showDialog">
      <img :src="imgUrl" alt="" style="width: 100%" />
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDEcnkT8atxmOnxtlQr4tUr55zf6IH2Yq2',
  SecretKey: '1oMfnkW6SZWN3WllU0IMBnBLGzb0BG6i'
})
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      imgUrl: '',
      currentUid: '',
      percentage: 0,
      showProgress: false
    }
  },
  computed: {
    disabled() {
      return this.fileList.length === 1
    }
  },
  methods: {
    preview(file) {
      this.imgUrl = file.url
      this.showDialog = true
    },
    remove(file, fileList) {
      // console.log(file)
      // console.log(fileList)
      this.fileList = fileList
    },
    // 上传之前检查
    beforeUpload(file) {
      // console.log(file)
      this.showProgress = true
      const types = ['image/jpeg', 'image/gif', 'image/bmp', 'image/png']
      if (!types.some((item) => item === file.type)) {
        this.$message.error('上传图片只能是 JPG、GIF、BMP、PNG 格式!')
        return false
      }
      // 1M = 1024KB  1KB=1024B
      if (file.size > 5 * 1024 * 1024) {
        this.$message.error('上传图片大小不能超过5M')
        return false
      }
      this.currentUid = file.uid // 通过uid保存当前文件的标识 - 上传成功之后修改list中的数据需要用到 - 因为需要找到修改哪一条数据
      return true
    },
    upload(params) {
      // console.log(params.file)
      if (params.file) {
        cos.putObject(
          {
            Bucket: 'qiqichen-1314103778', // 存储桶
            Region: 'ap-beijing', // 地域
            Key: params.file.name, // 文件名
            StorageClass: 'STANDARD', // 存储方式 - 标准模式
            Body: params.file, // 要上传的 文件对象
            onProgress: (params) => {
              // 进度的回调函数  - 要用到this的地方一定要记得写箭头函数
              console.log(params) // 获得上传的进度比
              this.percentage = params.percent * 100
            }
          },
          (err, data) => {
            console.log(err || data)
            if (!err && data.statusCode === 200) {
              // 表示上传成功
              console.log(11)
              if (this.fileList.length !== 0) {
                this.fileList = this.fileList.map((item) => {
                  if (item.uid === this.currentUid) {
                    return { url: 'http://' + data.Location, upload: true }
                  }
                  return item
                })
              } else {
                this.fileList.push({
                  // uid: params.file.uid,
                  name: params.file.name,
                  url: 'http://' + data.Location,
                  upload: true
                })
              }
              // 上传成功之后，隐藏进度条，将百分比归零
              setTimeout(() => {
                this.showProgress = false
                this.percentage = 0
              }, 1000)
            }
          }
        )
      }
    }
  }
}
</script>

<style>
.disabled .el-upload--picture-card {
  display: none;
}
</style>
